var express = require('express')
var router = express.Router()
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var fs = require('fs')
var unzip = require('unzip')   //解压zip压缩文件
var db = require('../public/javascripts/db')
var util = require('../public/javascripts/utils')


router.post('/', multipartMiddleware, (req, res, next) => {
    // console.log(req)
    // console.log(req.body)
    console.log(JSON.parse(req.body.alinfo))
    var data = JSON.parse(req.body.alinfo)
    var name = req.files.file.path.split('\\')
    name.pop()
    var savePath = name.join('\\')
    var filePath = savePath + '\\' + new Date().getTime() + '.zip';
    // console.log('filePath', filePath)
    // console.log('savePath', savePath)
    fs.rename(req.files.file.path, filePath, (err) => {
        if (err) {
            throw err
        } else {
            console.log('success fileName')
            fs.createReadStream(filePath).pipe(unzip.Extract({path: savePath}))
        }
    })
    var sql = 'SELECT * FROM algorithms';
    db.query(sql, (err, result) => {
        if (err) {
            throw err
            return
        }
        var len = result.length - 1
        len = result[len].id + 1
        // var sql2 = "INSERT INTO `algorithms` (algorithm_order) VALUES (?)";
        var sql = "INSERT INTO `algorithms` (name,nick,gpu_cpu,output_img,output_args,language,description,function,modified_time,algorithm_order) VALUES (?,?,?,?,?,?,?,?,?,?)";
        var sqlParams = [data.name, data.nick, data.gpu_cpu, data.output_img, data.output_args, data.language, data.description, 0, util.getTime(), len]
        db.query(sql, sqlParams, (err1, result1) => {
            if (err1) {
                throw err1
                return
            }
            console.log(result.length)
            res.send({msg: len})
        })
    })
})

module.exports = router